package com.kfm.hotel.controller;

import com.kfm.hotel.config.HotelProperties;
import com.kfm.hotel.domain.RoomImage;
import com.kfm.hotel.domain.SysUser;
import com.kfm.hotel.service.RoomImageService;
import com.kfm.hotel.util.Constant;
import com.kfm.hotel.util.R;
import net.bytebuddy.utility.nullability.AlwaysNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private HotelProperties properties;

    @Autowired
    private RoomImageService service;

    @GetMapping
    public ModelAndView upload() {
        ModelAndView modelAndView = new ModelAndView("upload");
        return modelAndView;
    }

    @PostMapping
    public R uploadFile(MultipartFile file, Integer id, HttpSession session) throws IOException {
        // 文件名
        String fileName = file.getOriginalFilename();
        // 文件后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 当前日期
        String date = LocalDate.now().toString().replace("-", "");

        // 重命名文件
        String saveName = date + "_" + System.currentTimeMillis() + suffixName;

        // 判断文件夹是否存在
        File dir = new File(properties.getUploadPath(), date);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String name = date + File.separator + saveName;
        // 保存文件
        // 创建 path 对象
        Path path = Paths.get(properties.getUploadPath(), name);
        // 写出文件
        file.transferTo(path);

        // 存入数据库
        RoomImage image = new RoomImage();
        image.setUrl(name);
        image.setRoomType(id);
        // 从 session 中获取当前用户id
        SysUser user = (SysUser) session.getAttribute(Constant.LOGIN_USER);
        image.setCreator(user.getId());
        service.save(image);

        return R.ok("上传成功");
    }
}
